package com.woniuxy.consumer;

import com.alibaba.fastjson2.JSON;
import com.rabbitmq.client.Channel;
import com.woniuxy.entity.Order;
import com.woniuxy.mapper.OrderMapper;
import com.woniuxy.util.RabbitmqConst;
import lombok.AllArgsConstructor;
import org.omg.CORBA.OMGVMCID;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitBootstrapConfiguration;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @BelongsProject: pigTrotterStore
 * @BelongsPackage: com.woniuxy.consumer
 * @Author: Quan
 * @Date: 2025/3/21 15:44
 */
@Component
@AllArgsConstructor
public class AddOrderToMapperConsumer {
	private OrderMapper orderMapper;

	/**
	 * @Description: 将订单添加到数据库中
	 * @Param: [msg]
	 * @return: void
	 * @Author: Quan
	 * @Date: 2025/3/21
	 */
	@RabbitListener(queues = RabbitmqConst.ADD_ORDER_TO_MAPPER_QUEUE)
	public void receive(String msg, Channel channel, Message message) {
		try {
			Order order = JSON.parseObject(msg, Order.class);
			orderMapper.addOrder(order);
			channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
		} catch (Exception e) {
			try {
				channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
			} catch (IOException ex) {
				throw new RuntimeException(ex);
			}
		}
	}
}
